package com.pan.note.config;

import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.pan.note.enumerate.TokenEnum;
import com.pan.note.dao.UserDao;
import com.pan.note.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 自定义拦截器
 */
@Component
@Slf4j
public class LoginHandlerInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头中的令牌
        String token = request.getHeader("token");
        Map<String, Object> map = new LinkedHashMap<>();
        try{
            JwtUtil.verify(token);
            return true;
        }catch (SignatureVerificationException e){
            log.info("无效签名");
            map.put("message","无效签名");
        }catch (TokenExpiredException e){
            log.info("token过期");
            map.put("message","token过期");
        }catch (AlgorithmMismatchException e){
            log.info("toen算法不一致");
            map.put("message","token算法不一致！");
        }catch (Exception e){
            log.info("token无效");
            map.put("message","token无效！");
        }
        //设置状态
        map.put("status",false);
        //将map转为json
        String json = new ObjectMapper().writeValueAsString(map);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);
        response.setStatus(405);
        return false;
    }
}
